import os
import re
from playwright.sync_api import sync_playwright, WebSocket
import subprocess

path = os.path

import ddddocr

ocr = ddddocr.DdddOcr(show_ad=False)
from playwright.async_api import async_playwright, WebSocket
import asyncio


browser_port = "9222"
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
edge_path = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"


def launch_chrome():
    process = subprocess.Popen([edge_path, f"--remote-debugging-port={browser_port}"])
    return process


USERNAME = "dwhuangxueying2"
PASSWORD = "Gmcc202506*"
storage_path = "./storage/ztc.json"


def main():

    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=False, args=["--remote-debugging-port=9222"]
        )
        if path.exists(storage_path):
            context = browser.new_context(
                ignore_https_errors=True, storage_state=storage_path
            )
        else:
            context = browser.new_context(ignore_https_errors=True)
        page = context.new_page()
        page.goto("http://10.243.168.52:9399/portal/")
        if not path.exists(storage_path):
            page.locator("#inputUserName").type(USERNAME)
            page.locator("#inputPasswd").type(PASSWORD)
            page.evaluate(
                "() => (document.querySelector('#imgVerifyCode').style.padding = '0px')"
            )  # 去掉按钮的padding
            page.locator("#imgVerifyCode").screenshot(path="code.jpg")

            with open(f"code.jpg", "rb") as f:
                img_bytes = f.read()

            res = ocr.classification(img_bytes)
            print(res)
            page.locator("#verificationCode").type(res)
            page.click("#btnLogin")

        def on_websocket(websocket: WebSocket):
            print(f"WebSocket 建立: {websocket.url}")

            def on_ws_frame_sent(frame):
                print(f"WebSocket 发送: {frame}")

            def on_ws_frame_received(frame):
                print(f"WebSocket 接收: {frame}")

            websocket.on("framereceived", on_ws_frame_received)
            websocket.on("framesent", on_ws_frame_sent)

        page.on("websocket", on_websocket)
        page.wait_for_timeout(10 * 60 * 1000)


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        context = await browser.new_context(ignore_https_errors=True)
        page = await context.new_page()

        async def on_websocket(ws: WebSocket):
            print(f"WebSocket 已建立: {ws.url}")

            async def on_ws_frame_sent(frame):
                print(f"WebSocket 发送: {frame}")

            async def on_ws_frame_received(frame):
                print(f"WebSocket 接收: {frame}")

            ws.on("framereceived", on_ws_frame_received)
            ws.on("framesent", on_ws_frame_sent)

            # 发送消息给服务器
            message = '{"action": "hello", "data": "from playwright"}'
            print(f"发送 WebSocket 消息: {message}")
            await ws.send_frame(text=message)

        page.on("websocket", on_websocket)
        await page.goto("http://10.243.168.52:9399/portal/")
        if not path.exists(storage_path):
            await page.locator("#inputUserName").type(USERNAME)
            await page.locator("#inputPasswd").type(PASSWORD)
            await page.evaluate(
                "() => (document.querySelector('#imgVerifyCode').style.padding = '0px')"
            )  # 去掉按钮的padding
            page.locator("#imgVerifyCode").screenshot(path="code.jpg")

            with open(f"code.jpg", "rb") as f:
                img_bytes = f.read()

            res = ocr.classification(img_bytes)
            print(res)
            await page.locator("#verificationCode").type(res)
            await page.click("#btnLogin")

        print("等待 WebSocket 通信...")
        await asyncio.sleep(10)  # 或者用事件驱动的方式等待

        await context.close()
        await browser.close()


if __name__ == "__main__":
    # main()
    asyncio.run(main())
